{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*** Using HANDLER:\n",
      "<!DOCTYPE html>\n",
      "\n",
      "*** Using REQUEST:\n",
      "<!DOCTYPE html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import urllib2\n",
    "LOGIN = 'wesley'\n",
    "PASSWORD = \"you'II Never Guess\"\n",
    "URL = 'http://www.baidu.com'\n",
    "REALM = 'Secure Archive'\n",
    "\n",
    "def handler_version(url):\n",
    "    from urlparse import urlparse\n",
    "    hdlr = urllib2.HTTPBasicAuthHandler()\n",
    "    hdlr.add_password(REALM,urlparse(url)[1],LOGIN,PASSWORD)\n",
    "    opener = urllib2.build_opener(hdlr)\n",
    "    urllib2.install_opener(opener)\n",
    "    return url\n",
    "def request_version(url):\n",
    "    from base64 import encodestring\n",
    "    req = urllib2.Request(url)\n",
    "    b64str = encodestring('%s:%s' % (LOGIN,PASSWORD))[:-1]\n",
    "    req.add_header('Authorization','basic %s' % b64str)\n",
    "    return req\n",
    "\n",
    "for funcType in ('handler','request'):\n",
    "    print '*** Using %s:' % funcType.upper()\n",
    "    url = eval('%s_version' % funcType)(URL)\n",
    "    f= urllib2.urlopen(url)\n",
    "    print f.readline()\n",
    "    f.close"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "eval?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import urllib\n",
    "from urllib import FancyURLopener"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "FancyURLopener.retrieve?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
